﻿@using OBUCare.Web.Infrastructure
@using OBUCare.Core.BL
@using OBUCare.Core.DataAccess;
@using OBUCare.Web.Models;
@using OBUCare.Core.Common;
@using OBUCare.Core.Models;
@{
    ObuDropDownListHlper ddlHelper = new ObuDropDownListHlper();
}
<link href="../../Content/tableCss.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/JqeryToDictionary.js"></script>
<h2 style="text-align: center; height: 100px;">元器件销售管理</h2>
<table width="100%">
    <tr>
        <td>标签号：@Html.TextBox("txtOUBNo")&nbsp;&nbsp;&nbsp;<input type="button" value="            " id="btnLoadOBU" style="background-image: url(@Url.Content("~/Content/images/button_search.gif")); width:150;height:30"/>
        </td>
    </tr>
    <tr>
        <td>
            <div id="divObu" style="display: none">
                @using (Html.BeginForm("ConfirmSell", "Parts", FormMethod.Post, new { @id = "form_id" }))
                {
                    @Html.ValidationSummary(true)
    
                    <table width="100%">
                        <tr style="height: 40px;">
                            <td width="20%">标签号：
                            </td>
                            <td width="30%">
                                <span id="lblOubNo"></span>
                            </td>
                            <td width="20%">发行日期：
                            </td>
                            <td width="30%">
                                <span id="lblIssueDate"></span>
                            </td>
                        </tr>
                        <tr style="height: 40px;">
                            <td>元器件：
                            </td>
                            <td>
                                @Html.Telerik().DropDownList().Name("PartType").HtmlAttributes(new { @style = "width:160px;" }).BindTo(ddlHelper.GetPartTypes("请选择", true, new KeyValuePair<string, string>(UIConstants.AllItemsValue.ToString(), "请选择"))).ClientEvents(events => events.OnChange("onPartsTypeChange"))
                            </td>
                            <td>厂商：
                            </td>
                            <td>
                                @Html.Telerik().DropDownList().Name("Supplier").BindTo(ddlHelper.GetSuppliers("请选择", true, new KeyValuePair<string, string>("请选择", "请选择"))).ClientEvents(e => e.OnChange("changeSpecs"))
                            </td>
                        </tr>
                        <tr style="height: 40px;">
                            <td>型号：
                            </td>
                            <td>
                                @Html.Telerik().DropDownList().Name("SpecName").HtmlAttributes(new { @style = "width:160px;" }).BindTo(ddlHelper.GetPartsSpecs(null, true)).ClientEvents(e => e.OnChange("changeStock"))
                            </td>
                            <td>剩余数量：
                            </td>
                            <td>
                                <span id="lblAmount">50000</span>
                            </td>
                        </tr>
                        <tr style="height: 40px;">
                            <td>销售金额：
                            </td>
                            <td>
                                @Html.Telerik().DropDownList().Name("price").HtmlAttributes(new { @style = "width:160px;" })
                            </td>
                            <td>备注：
                            </td>
                            <td>
                                @Html.TextBox("Comments", "", new { @style = "width:160px;" })
                            </td>
                        </tr>
                    </table>
                }
            </div>
        </td>
    </tr>
    <tr>
        <td>
            <input type="button" value="加入批量提交列表" onclick="addNewRow();" style="width: 150px;" />
            <input type="button" value="直接提交" style="width: 150px;" onclick="submitData();" />
            <input type="button" value="批量提交" style="width: 150px;" onclick="batchSubmitData();" />
        </td>
    </tr>
    <tr>
        <td>
            <div>
                @(Html.Telerik().Grid<PartsSellInfo>()
                    .Name("Grid")
                    .DataKeys(keys => keys.Add(c => c.ID))
                    .Sortable(sorting => sorting.SortMode(GridSortMode.SingleColumn))
                            .DataBinding(dataBinding => dataBinding
                                .Ajax()
                                .Delete("Remove", "Parts")
                                        )

                    .Columns(columns =>
                    {
                        columns.Bound(o => o.Obu_No).Width("15%");
                        columns.Bound(o => o.IssueDate).Format("{0:yyyy-MM-dd}").Width("10%");
                        columns.Bound(o => o.PartType).Width("10%");
                        columns.Bound(o => o.Supplier).Width("8%");
                        columns.Bound(o => o.Spec).Width("8%");
                        columns.Bound(o => o.Price).Width("8%");
                        columns.Bound(o => o.Comments).Width("8%");
                        columns.Command(commands =>
                        {
                            commands.Delete().ButtonType(CommonStyleForUI.Grid_ButtuonType).Text("移除");
                        }).Width("8%").Title("操作");
                    }).TableHtmlAttributes(new { @style = "width:100%" })
                            .ClientEvents(events =>
                            {
                                events.OnDelete("onDelete");
                            })
                        //.Resizable(resizing => resizing.Columns(true))
                        //   .Scrollable(scroll => scroll.Height(CommonStyleForUI.Grid_Height))
                        .Selectable()
                    )
            </div>
        </td>
    </tr>
</table>
<script language="javascript" type="text/javascript">

    $().ready(function () {
        //初始化价格
        onPartsTypeChange(null);

        $("#btnLoadOBU").click(function () {
            var value = $('#txtOUBNo').val();
            loadObuInfo(value);
        });
        changeSpecs(null);
    });

    function loadObuInfo(value) {
        value = $.trim(value);
        if (value.StringIsNullOrEmpty()) {
            alert("请输入标签号");
            return;
        }
        if (value.length != 16) {
            alert("请输入16位标签号");
            return false;
        }
        var surl = "/parts/GetObuInfo?id=" + value;
        $.ajax({
            type: "Get",
            url: surl,
            cache: false,
            dataType: "json",
            success: function (data) {
                if (data.success) {
                    document.getElementById("divObu").style.display = "inline";

                    var PartsType = $('#PartType').data('tDropDownList');
                    PartsType.value(data.partsType);

                    var Supplier = $('#Supplier').data('tDropDownList');
                    if (Supplier != null) {
                        Supplier.value(data.SupplierID);
                    }
                    var SpecName = $('#SpecName').data('tDropDownList');
                    if (data.SpecList == null) {
                        changeSpecs(null);
                    } else {
                        SpecName.dataBind(data.SpecList);
                        SpecName.value(data.Spec);
                    }

                    if (data.partsType != "请选择") {
                        var bindDataTypeUrl = '@Url.Action("GetDDLPartsPrie", "Parts")';
                        var ddlPartType = $("#PartType").data("tDropDownList");
                        bindDataTypeUrl += "/" + ddlPartType.value();
                        BindDropDownList("", bindDataTypeUrl, 'price');
                    }

                    $("#lblOubNo").text(data.OubNo);
                    $("#lblIssueDate").text(data.IssueDate);
                    $("#lblAmount").text(data.StockNum);
                }
                else {
                    document.getElementById("divObu").style.display = "none";
                    alert(data.message);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var err = XMLHttpRequest + "<br />" + textStatus + "<br />" + errorThrown;
                alert(err);
            }
        });
    }


    //保存用户提交的数据
    var data = [];

    function addNewRow() {
        var value = $("#lblOubNo").text();
        value = $.trim(value);
        if (value.StringIsNullOrEmpty()) {
            alert("请输入标签号");
            return false;
        }
        if ($('#SpecName').val() == "请选择" || $('#SpecName').val() == "0") {
            alert("请选择型号");
            return false;
        }
        var stockCount = $("#lblAmount").text();
        stockCount = $.trim(stockCount);

        if (stockCount == "0" || data.length == stockCount) {
            alert("该型号的元器件已无库存，请选择其他型号或进行入库划拨");
            return false;
        }

        //$.post();
        var obuN0 = $("#lblOubNo").text();
        var issueDate = $("#lblIssueDate").text();
        var ddlPartType = $("#PartType").data("tDropDownList");
        var ddlSupplier = $("#Supplier").data("tDropDownList");
        var ddlSpec = $("#SpecName").data("tDropDownList");
        var amount = $("#lblAmount").text();
        var ddlPrice = $("#price").data("tDropDownList"); //tDropDownList
        var comments = $("#Comments").val();
        var info = { ID: data.length, Obu_No: obuN0, IssueDate: issueDate, PartTypeID: ddlPartType.value(), PartType: ddlPartType.text(), SupplierID: ddlSupplier.value(), Supplier: ddlSupplier.text(), SpecID: ddlSpec.value(), Spec: ddlSpec.text(), Price: ddlPrice.value(), Comments: comments };

        data.push(info);

        rebindData();
        return true;
    }


    function onDelete(e) {

        var dataItem = e.dataItem;
        data.Remove(dataItem.ID);
        e.preventDefault();

        rebindData();
    }

    function rebindData() {
        for (x in data) {
            var info = data[x];
            info.ID = x;
        }

        var grid = $("#Grid").data("tGrid");
        grid.dataBind(data);
    }

    //元器件类型发生change事件
    function onPartsTypeChange(e) {
        var bindDataTypeUrl = '@Url.Action("GetDDLPartsPrie", "Parts")';
        var ddlPartType = $("#PartType").data("tDropDownList");
        bindDataTypeUrl += "/" + ddlPartType.value();
        BindDropDownList("", bindDataTypeUrl, 'price');

        var partType = $('#PartType').val();
        var value = $('#SpecName').val();
        $.post("/Parts/getStockNumBy", { "specID": value, "partID": partType }, function (data) {
            $("#lblAmount").text(data.StockCount);
        });

        changeSpecs(null);
    }
    //厂商下拉效果
    function changeSpecs(e) {
        var SpecName = $('#SpecName').data('tDropDownList');
        var value = $('#Supplier').data('tDropDownList').value();
        var partType = $('#PartType').data('tDropDownList').value();
        // var value = e.currentTarget.value;
        //        if ($("#PartType").val() == "请选择") {
        //            alert("请选择元器件");
        //            return false;
        //        }
        //        else {
        $.post("/Parts/_getSpecs", { "supplierID": value, "PartsType": partType }, function (data) {
            SpecName.dataBind(data);
            if (SpecName != null) {
                SpecName.select(0);
            }
        });
        //        }
    }

    function changeStock(e) {
        var partType = $('#PartType').val();
        var value = e.currentTarget.value;
        $.post("/Parts/getStockNumBy", { "specID": value, "partID": partType }, function (data) {
            $("#lblAmount").text(data.StockCount);
        });
    }

    //绑定Dropdownlist
    function BindDropDownList(value, url, ctrID) {

        var ddlCtr = $('#' + ctrID).data('tDropDownList');
        ddlCtr.loader.showBusy();

        $.get(url, function (data) {
            ddlCtr.dataBind(data);
            ddlCtr.loader.hideBusy();
            if (!value.StringIsNullOrEmpty())
                ddlCtr.value(value);
            else
                ddlCtr.select(0);
        });
    }

    //批量提交
    function batchSubmitData() {
        if (data.length <= 0) {
            alert("暂时没有数据可提交");
            return;
        }
        var str = $.toDictionary(data); //$.toJSON(data); //JSON.stringify(data);
        $.ajax({
            type: "POST",
            url: "/parts/ConfirmSell",
            data: str,
            cache: false,
            dataType: "json",
            success: function (data) {

                if (data.success) {
                    alert("提交成功");
                    url = "/Transaction/Index/";
                    window.location.href = url;//"/parts/sell";
                }
                else {
                    alert(data.message);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var err = XMLHttpRequest + "<br />" + textStatus + "<br />" + errorThrown;
                alert(err);
            }
        });
    }

    //直接提交
    function submitData() {
        if (addNewRow())
            batchSubmitData();
    }
</script>
